#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <cstdio>
#include <unistd.h>


const int BUF_SIZE = 1024;

int main(int argc, char *argv[])
{
    int listener = 0;
    sockaddr_in address;
    char buffer[BUF_SIZE];
    int bytes_read = 0;

    listener = socket(AF_INET, SOCK_STREAM, 0);
    if (listener < 0) {
        perror("Unable to create socket");
        return 1;
    }
    address.sin_family = AF_INET;
    address.sin_port = htons(5001);
    address.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(listener, (sockaddr *)&address, sizeof(address)) < 0) {
        perror("Unable to bind socket");
        return 1;
    }
    listen(listener, SOMAXCONN);

    int acceptor = 0;

    while (true) {
        acceptor = accept(listener, NULL, NULL);
        if (acceptor < 0) {
            perror("Unable to accept connection");
        }
        while (true) {
            bytes_read = recv(acceptor, buffer, BUF_SIZE, 0);
            if (bytes_read <= 0) break;
            send(acceptor, buffer, bytes_read, 0);
        }
        close(acceptor);
    }
    return 0;
}
